import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  message,
  Modal,
} from 'antd';

import { DetailInfoItem } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;

interface SmallWhiteAddProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: DetailInfoItem;
  logisList: any;
  location: {
    state?: { id: number };
  };
}

interface SmallWhiteAddState {
  deviceNumList: { id: number; value: string; disabled: boolean }[];
  per_deviceNumList: string;
  delVisible: boolean;
  saveOrDelValues: {
    isValid: number;
    accountId: number;
    deviceNo: string;
  };
}

@connect(({
  cooperationCompanySmallWhiteAdd: { detailInfo, logisList },
}: any) => ({
  detailInfo,
  logisList,
}))
class SmallWhiteInfoAddElem extends Component<SmallWhiteAddProps, SmallWhiteAddState> {
  timer: any = null;

  state: SmallWhiteAddState = {
    deviceNumList: [{ id: 0, value: '', disabled: false }],
    per_deviceNumList: '',
    delVisible: false,
    saveOrDelValues: {
      isValid: 0,
      accountId: 0,
      deviceNo: '',
    },
  };

  static getDerivedStateFromProps(nextProps: SmallWhiteAddProps, perState: SmallWhiteAddState) {
    const { detailInfo } = nextProps;
    const { per_deviceNumList } = perState;
    if (detailInfo && detailInfo.deviceNoList && detailInfo.deviceNoList !== per_deviceNumList) {
      const new_deviceNoList = detailInfo.deviceNoList.split(',')
        .map((item: any, index: number) => {
          item = {
            id: index,
            value: item,
            disabled: true,
          };
          return item;
        });
      return {
        deviceNumList:
          new_deviceNoList.length > 0 ? new_deviceNoList : [{ id: 0, value: '', disabled: false }],
        per_deviceNumList: detailInfo.deviceNoList,
      };
    }
    return null;
  }

  componentDidMount() {
    const { location: { state } } = this.props;
    if (state) {
      const { id } = state;
      this.fetchAction('fetch', { id });
    }
    this.fetchAction('fetchLogis', { name: '' });
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  handleSearchLogs = (name: string) => {
    clearTimeout(this.timer);

    this.timer = setTimeout(() => {
      this.fetchAction('fetchLogis', { name });
    }, 500);
  };

  handleChangeDevice = (e: any, id: number) => {
    const { deviceNumList } = this.state;
    const params = [...deviceNumList];
    params[id].value = e.target.value;
    this.setState({ deviceNumList: params });
  };

  handleSaveNo = () => {
    // 继续新增输入框
    const { deviceNumList } = this.state;
    this.setState({
      deviceNumList: [
        ...deviceNumList,
        {
          id: deviceNumList[deviceNumList.length - 1].id + 1,
          value: '',
          disabled: false,
        },
      ],
    });
  };

  handleDelNo = (index: number) => {
    // 删除输入框
    const { form: { resetFields } } = this.props;
    resetFields(['device']);

    const { deviceNumList } = this.state;
    const Del_deviceNoList = [...deviceNumList];
    Del_deviceNoList.splice(index, 1);
    Del_deviceNoList.map((item: any, key: number) => {
      item.id = key;
      return item;
    });

    this.setState({
      deviceNumList: Del_deviceNoList,
    });
  };

  handleSave = (values: any) => {
    // 保存已输入编号
    if (!values.value) {
      message.error('请输入设备编号');
      return;
    }

    const { detailInfo: { id } } = this.props;
    const params = {
      id,
      isValid: 1,
      accountId: id,
      deviceNo: values.value,
    };
    this.fetchAction('saveOrDelNo', params);
  };

  handleChangeDelModal = (delVisible: boolean, values?: any) => {
    const { detailInfo } = this.props;
    this.setState({
      saveOrDelValues: {
        isValid: values ? 2 : 0,
        accountId: values ? detailInfo.id : 0,
        deviceNo: values ? values.value : '',
      },
      delVisible,
    });
  };

  handleDelSubmit = () => {
    // 删除编号
    const { saveOrDelValues } = this.state;
    const { detailInfo: { id } } = this.props;
    const params = { id, ...saveOrDelValues };
    this.fetchAction('saveOrDelNo', params);

    this.handleChangeDelModal(false);
  };

  handleSubmit = () => {
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { location: { state } } = this.props;
      if (state) {
        values = {
          ...values,
          id: state.id,
          disabled: false,
        };
      }
      const params = {
        ...values,
        logisId: values.logisId ? values.logisId.key : '',
        deviceNoList: values.device ? values.device.join(',') : '',
      };
      delete params.device;

      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `cooperationCompanySmallWhiteAdd/${typeName}`,
      payload,
    });
  };

  renderdeviceNoList = () => {
    const NoList: any = [];
    const { deviceNumList } = this.state;
    const {
      form: { getFieldDecorator },
      location: { state },
    } = this.props;

    deviceNumList.map((item: any, index: number) => {
      NoList.push(
        <Col md={8} sm={24} key={item.id} className="marginB20">
          <Item label="设备编号" colon={false}>
            <div style={{ display: 'flex' }}>
              <div style={{ flex: 1 }}>
                {getFieldDecorator(`device[${index}]`, {
                  initialValue: item.value,
                  rules: [{ required: true, message: '请输入设备编号' }],
                })(
                  <Input
                    allowClear
                    placeholder="请输入"
                    disabled={item.disabled}
                    onChange={e => this.handleChangeDevice(e, item.id)}
                  />,
                )}
              </div>
              {!item.disabled && state && state.id && (
                <span className="operLink marginL16" onClick={() => this.handleSave(item)}>
                  保存
                </span>
              )}
              {item.disabled && (
                <span
                  className="operLink marginL16"
                  onClick={() => this.handleChangeDelModal(true, item)}
                >
                  删除
                </span>
              )}
              {((!state && index !== 0) || (index !== 0 && !item.disabled)) && (
                <span className="operLink marginL16" onClick={() => this.handleDelNo(index)}>
                  删除
                </span>
              )}
            </div>
          </Item>
        </Col>,
      );
      return null;
    });

    return NoList;
  };

  render() {
    const { delVisible } = this.state;
    const {
      form: { getFieldDecorator },
      detailInfo,
      logisList,
      location: { state },
    } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Form hideRequiredMark className="tableListForm">
          <Card
            bordered={false}
            title="基础信息"
            className="paddingB10"
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="设备名称">
                  <div>小白盒子</div>
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　类型">
                  <div>物流中心</div>
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="状态" colon={false}>
                  {getFieldDecorator('status', {
                    initialValue: detailInfo.status,
                    rules: [{ required: true, message: '请选择状态' }],
                  })(
                    <Select disabled={Boolean(state)} placeholder="请选择">
                      <Option value={1}>启用</Option>
                      <Option value={0}>禁用</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId', {
                    initialValue: {
                      key: detailInfo.logisId || '',
                      label: detailInfo.logisName || '',
                    },
                    rules: [{ required: true, message: '请选择物流中心' }],
                  })(
                    <Select
                      showSearch
                      placeholder="请选择"
                      labelInValue
                      disabled={Boolean(state)}
                      onSearch={this.handleSearchLogs}
                      filterOption={(input: any, option: any) => option.props.children
                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
          </Card>

          <Card
            bordered={false}
            title="合作方系统方案"
            className="paddingB10"
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="合作账号" colon={false}>
                  {getFieldDecorator('account', {
                    initialValue: detailInfo.account,
                    rules: [{ required: true, message: '请输入合作账号' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="合作密码" colon={false}>
                  {getFieldDecorator('password', {
                    initialValue: detailInfo.password,
                    rules: [{ required: true, message: '请输入合作密码' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
            </Row>
          </Card>

          <Card
            bordered={false}
            title="设备绑定"
            extra={
              <span className="operLink" onClick={this.handleSaveNo}>
                继续新增设备编号
              </span>
            }
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>{this.renderdeviceNoList()}</Row>
          </Card>

          <Card bordered={false}>
            <Button type="primary" onClick={this.handleSubmit}>
              保存
            </Button>
            <Button type="primary" className="marginL16" ghost onClick={() => router.goBack()}>
              取消
            </Button>
          </Card>

        </Form>
        <Modal
          visible={delVisible}
          onOk={this.handleDelSubmit}
          onCancel={() => this.handleChangeDelModal(false)}
        >
          <p>该设备编号已保存，是否删除该设备编号？</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<SmallWhiteAddProps>()(SmallWhiteInfoAddElem);
